/*
    1.理由路由到底是什么？（提示：从路径去想）
    2.定义购物车路由(可以认为，一种路由，就是一种请求),写出相关代码并调试。
    用户注册，用户更新购物车，用户读取购物车，彻底删除用户
    3.找不到时，404

    switch(path){
        case "":
        case "/":
            break;
        case "/updateCart"
            break;
    }

*/
let className = require("./p4-module")
const http = require('http')
const hostname = '127.0.0.1';
let CN = new className.CUser("lyshsd")
const port = 3030;
const fs = require("fs")

function startServer2() {
    const server = http.createServer((require, response) => {

        switch (require.url) {
            case "/":
                response.writeHead(200, {
                    'Content-Type': "text/html"
                })
                fs.createReadStream(__dirname + "/index.html", "utf8").pipe(response)
                console.log("这是首页");
                break;

            case "/renewCart":
                response.writeHead(200, {
                    'Content-Type': "text/html"
                })
                var readerStream = fs.createReadStream(CN.用户名 + '.txt')
                var writerStream1 = fs.createWriteStream(CN.用户名 + '/cart.txt');
                readerStream.pipe(writerStream1);
                fs.createReadStream(__dirname + "/renew.html", "utf8").pipe(response)
                console.log("用户更新了购物车，cart.txt创建成功");
                break;

            case "/readCart":
                response.writeHead(200, {
                    'Content-Type': "application/json"
                })
                fs.createReadStream(__dirname + "/" + CN.用户名 + "/cart.txt", "utf8").pipe(response)
                console.log("用户读取了购物车");
                break;
            case "/delUser":
                var files = fs.readdirSync(CN.用户名); //读取该文件夹

                files.forEach(function(file) {

                    var stats = fs.statSync(CN.用户名 + '/' + file);

                    if (stats.isDirectory()) {

                        emptyDir(CN.用户名 + '/' + file);

                    } else {

                        fs.unlinkSync(CN.用户名 + '/' + file);

                        console.log("删除文件" + CN.用户名 + '/' + file + "成功");

                    }

                })
                fs.rmdir(CN.用户名, function() {
                    console.log("删除目录成功")
                })

                response.writeHead(200, {
                    'Content-Type': "text/html"
                })
                fs.createReadStream("/del.html", "utf8").pipe(response)
                console.log("用户删除了");
                break;
            default:
                response.writeHead(200, {
                    'Content-Type': "text/html"
                })
                fs.createReadStream(__dirname + "/404.html", "utf8").pipe(response)
                console.log("用户读取了购物车");
        }
    })

    server.listen(port, hostname, () => {
        console.log(`服务器运行在 http://${hostname}:${port}/`); //注意这里的模板字符
    })
}

exports.startServer2 = startServer2